package com.hmy.infrastructure.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

/**
 * @ClassName: SpringContextUtil
 * @Description: 存放spring上下文环境, 当spring环境创建完成后，会触发onEnvFinished
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {


    public final static Logger logger = LoggerFactory.getLogger(SpringContextUtil.class);


    private static WebApplicationContext webContext = null;

    private static ApplicationContext applicationContext;

    public static boolean needToSetWebContext = true;

    /*****
     * 获取Spring-mvc应用上下文环境
     * */
    public static WebApplicationContext getWebContext() {
        return webContext;
    }

    public static void setWebContext(WebApplicationContext webContext) {
        SpringContextUtil.webContext = webContext;
        needToSetWebContext = false;
    }

    /*****
     * 获取Spring应用上下文环境
     * ******/
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }


    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        SpringContextUtil.applicationContext = arg0;
    }

    /**
     * 获取对象
     *
     * @param name
     * @return Object
     * @throws BeansException
     */
    public static Object getBean(String name) throws BeansException {
        Object obj = null;
        try {
            if (webContext != null) {
                obj = webContext.getBean(name);
            } else {
                obj = applicationContext.getBean(name);
            }
        } catch (Exception ex) {
            logger.warn("try the Spring ApplicationContext Cannot get the bean [" + name + "]");
        }
        return obj;
    }

    /**
     * 获取对象
     *
     * @param name
     * @return Object
     * @throws BeansException
     */
    public static Object getBean(String name, boolean outputErrorLog) throws BeansException {
        Object obj = null;
        try {
            if (webContext != null) {
                obj = webContext.getBean(name);
            } else {
                obj = applicationContext.getBean(name);
            }
        } catch (Exception ex) {
            if (logger != null && outputErrorLog) {
                logger.error("{}", ex);
            }
            logger.warn("try the Spring ApplicationContext Cannot get the bean [" + name + "]");
        }
        return obj;
    }
}
